//
//  ConfirmOrderViewController.m
//  CityUCanteen
//
//  Created by Sierra on 2018/3/30.
//  Copyright © 2018年 iFlytek. All rights reserved.
//

#import "ConfirmOrderViewController.h"
#import "BRPickerView.h"
#import "XZPickView.h"


#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>

#define kScreenBounds [UIScreen mainScreen].bounds


@implementation Product


@end


@interface ConfirmOrderViewController ()<XZPickViewDelegate, XZPickViewDataSource>

@property (nonatomic,strong) XZPickView * pickView;

@property (nonatomic,copy) NSDictionary * dateDic;
@property (nonatomic,copy) NSString * weekStr;
@property (nonatomic,copy) NSString * timeStr;
@property (nonatomic, strong) NSDate *selectDate;
@property (nonatomic, assign) NSInteger currentSelectDay;


@property (weak, nonatomic) IBOutlet UIButton *pickerTimeBtn;

@property (weak, nonatomic) IBOutlet UIButton *pickerPaymentBtn;


@property (weak, nonatomic) IBOutlet UILabel *typeLabel;

@property (weak, nonatomic) IBOutlet UILabel *subTypeLabel;

@end

@implementation ConfirmOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Confirm Payment Order Info";

    
    self.typeLabel.text = self.tempData1;
    self.subTypeLabel.text = self.tempData2;
    
    
    
    [self generateData];
}

#pragma mark -
#pragma mark   ==============产生随机订单号==============


- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}




#pragma mark -
#pragma mark   ==============产生订单信息==============

- (void)generateData{
    NSArray *subjects = @[@"1",
                          @"2",@"3",@"4",
                          @"5",@"6",@"7",
                          @"8",@"9",@"10"];
    NSArray *body = @[@"我是测试数据",
                      @"我是测试数据",
                      @"我是测试数据",
                      @"我是测试数据",
                      @"我是测试数据",
                      @"我是测试数据",
                      @"我是测试数据",
                      @"我是测试数据",
                      @"我是测试数据",
                      @"我是测试数据"];
    
    if (nil == self.productList) {
        self.productList = [[NSMutableArray alloc] init];
    }
    else {
        [self.productList removeAllObjects];
    }
    
    for (int i = 0; i < [subjects count]; ++i) {
        Product *product = [[Product alloc] init];
        product.subject = [subjects objectAtIndex:i];
        product.body = [body objectAtIndex:i];
        
        product.price = 0.01f+pow(10,i-2);
        [self.productList addObject:product];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)chooseTimeBtnClick:(UIButton *)sender {
    
    
    NSLog(@"%s",__func__);
    self.dateDic = [self LHGetStartTime];
    self.weekStr = self.dateDic[@"week"][0];
    NSDate *date  = [[self.dateDic[@"time"] objectAtIndex:0] objectAtIndex:0];
    self.timeStr = [self XZGetTimeStringWithDate:date dateFormatStr:@"HH:mm"];
    [self.pickView reloadData];
    //[self.userNumPickView selectRow:0 inComponent:0 animated:NO];
    [[UIApplication sharedApplication].keyWindow addSubview:self.pickView];
    [self.pickView show];

    

    
}

- (IBAction)choosePaymentWayBtnClick:(UIButton *)sender {
    [BRStringPickerView showStringPickerWithTitle:@"Payment Method" dataSource:@[@"Ali Pay", @"Wechat Pay", @"Apple Pay",@"Samsung Pay",@"Paypal",@"Credit Card"] defaultSelValue:@"Ali Pay" isAutoSelect:YES resultBlock:^(id selectValue) {
        NSLog(@"%@",selectValue);
        [self.pickerPaymentBtn setTitle:[NSString stringWithFormat:@"Payment: %@",selectValue] forState:UIControlStateNormal];
    }];
}


-(void)pickView:(XZPickView *)pickerView confirmButtonClick:(UIButton *)button{
    
    NSInteger left = [pickerView selectedRowInComponent:0];
    NSInteger right = [pickerView selectedRowInComponent:1];
    self.selectDate = [[self.dateDic[@"time"] objectAtIndex:left] objectAtIndex:right];
    
    [self.pickerTimeBtn setTitle:[NSString stringWithFormat:@"Pick-up Time: %@",[self XZGetTimeStringWithDate:self.selectDate dateFormatStr:@"HH:mm:ss"]] forState:UIControlStateNormal];
    
}

-(NSInteger)pickerView:(XZPickView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    //时间
    if (component == 0) {
        return [self.dateDic[@"week"] count];
    }else{
        NSInteger whichWeek = [pickerView selectedRowInComponent:0];
        return [[self.dateDic[@"time"] objectAtIndex:whichWeek] count];
    }
}

-(void)pickerView:(XZPickView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if(component == 0){
        self.currentSelectDay = [pickerView selectedRowInComponent:0];
        [pickerView pickReloadComponent:1];
        self.weekStr = self.dateDic[@"week"][row];
        NSArray *arr = [[self.dateDic objectForKey:@"time"] objectAtIndex:self.currentSelectDay];
        NSDate *date = [arr objectAtIndex:[pickerView selectedRowInComponent:1]];
        self.timeStr = [self XZGetTimeStringWithDate:date dateFormatStr:@"HH:mm"];
    }else{
        NSInteger whichWeek = [pickerView selectedRowInComponent:0];
        NSDate *date = [[self.dateDic[@"time"] objectAtIndex:whichWeek] objectAtIndex:row];
        self.timeStr = [self XZGetTimeStringWithDate:date dateFormatStr:@"HH:mm"];
    }
    
}

-(NSString *)pickerView:(XZPickView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if(component == 0){
        return self.dateDic[@"week"][row];
    }else{
        NSArray *arr = [[self.dateDic objectForKey:@"time"] objectAtIndex:self.currentSelectDay];
        NSDate *date = [arr objectAtIndex:row];
        NSString *str = [self XZGetTimeStringWithDate:date dateFormatStr:@"HH:mm"];
        return str;
    }
}

-(NSInteger)numberOfComponentsInPickerView:(XZPickView *)pickerView{
    return 2;
}

#pragma mark -

- (NSString *)XZGetTimeStringWithDate:(NSDate *)date dateFormatStr:(NSString *)dateFormatStr {
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = dateFormatStr;
    return [format stringFromDate:date];
}

- (NSDictionary *)LHGetStartTime {
    // 获取当前date
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDictionary *weekDict = @{@"2" : @"周一", @"3" : @"周二", @"4" : @"周三", @"5" : @"周四", @"6" : @"周五", @"7" : @"周六", @"1" : @"周日"};
    // 日期格式
    NSDateFormatter *fullFormatter = [[NSDateFormatter alloc] init];
    fullFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    // 获取当前几时(晚上23点要把今天的时间做处理)
    NSInteger currentHour = [calendar component:NSCalendarUnitHour fromDate:date];
    // 存放周几和时间的数组
    NSMutableArray *weekStrArr = [NSMutableArray array];
    NSMutableArray *detailTimeArr = [NSMutableArray array];
    // 设置合适的时间
    for (int i = 0; i < 1; i++) {
        NSDate *new = [calendar dateByAddingUnit:NSCalendarUnitDay value:i toDate:date options:NSCalendarMatchStrictly];
        NSInteger week = [calendar component:NSCalendarUnitWeekday fromDate:new];
        // 周几
        NSString *weekStr = weekDict[[NSString stringWithFormat:@"%ld",week]];
        NSString *todayOrOther = @"";
        if (i == 0) {
            todayOrOther = @"今天";
        }
        
//        else if (i == 1) {
//            todayOrOther = @"明天";
//        }else if (i == 2){
//            todayOrOther = @"后天";
//        }
        // 今天周几 明天周几 后天周几
        NSString *resultWeekStr = [NSString stringWithFormat:@"%@ %@",todayOrOther,weekStr];
        [weekStrArr addObject:resultWeekStr];
        
        NSInteger year = [calendar component:NSCalendarUnitYear fromDate:new];
        NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:new];
        NSInteger day = [calendar component:NSCalendarUnitDay fromDate:new];
        
        // 把符合条件的时间筛选出来
        NSMutableArray *smallArr = [NSMutableArray array];
        for (int hour = 0; hour < 24; hour++) {
            for (int min = 0; min < 60; min ++) {
                if (min % 30 == 0) {
                    NSString *tempDateStr = [NSString stringWithFormat:@"%ld-%ld-%ld %d:%d",year,month,day,hour,min];
                    
                    NSDate *tempDate = [fullFormatter dateFromString:tempDateStr];
                    // 今天 之后的时间段
                    if (i == 0) {
                        if ([calendar compareDate:tempDate toDate:date toUnitGranularity:NSCalendarUnitHour] == 1) {
                            [smallArr addObject:tempDate];
                        }
                    }else{
                        [smallArr addObject:tempDate];
                    }
                }
            }
        }
        [detailTimeArr addObject:smallArr];
    }
    // 晚上23点把今天对应的周几和今天的时间空数组去掉
    if (currentHour == 23) {
        [weekStrArr removeObjectAtIndex:0];
        [detailTimeArr removeObjectAtIndex:0];
    }
    NSDictionary *resultDic = @{@"week" : weekStrArr , @"time" : detailTimeArr};
    return resultDic;
}

#pragma mark - getter methods

-(XZPickView *)pickView{
    if(!_pickView){
        _pickView = [[XZPickView alloc]initWithFrame:kScreenBounds title:@"Please Select"];
        _pickView.delegate = self;
        _pickView.dataSource = self;
    }
    return _pickView;
}


- (IBAction)backItemClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)confirmItemClick:(UIButton *)sender {
    
    /*
     *点击获取prodcut实例并初始化订单信息
     */
    Product *product = [self.productList objectAtIndex:2];
    
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2088421262979385";
    NSString *seller = @"betterkitchen@163.com";
    NSString *privateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMr7bDyRyKWs9GkDkCSj5HZaAlk5I2HBJEj2Xhe6rSQnIu3tb3YY+TXLbOPIlT0p/9dslbBxOWz/zjY0QXry51r4MLbz+j7wEwvdLCFQsdiRRURD/1tcVI7Rb1kJqTew/OSWizkuDhD5GZkVi+9RiI92r2aCyaQF5YOdr9cRKogdAgMBAAECgYAFE4qebSruccffBHbLY8nn59JdNt+ap0DoDjlGMKX53Hy0JJcABhndbYv4mmCZGf7K/W0072/3OOKIWoA0ufRtN481g3NunZ5t0aEonxGr3kPz9GLv+YtziAcOgvOUaYQq5eqOdd6/L/lMewqEvJm0pzlDhdUkPt5RiXHrLFOTBQJBAPUa0NzgB2PNZhBVUI/1J/nOYNzBKZudDzL1r/GCKudCv1ohN+p1M3OTgfeLcz0uefyotXMY83FrqfWPzvoOT7sCQQDUAUUby/Q4i7W5AZK1cgoZmddSzG33yUroQziiXnEMfLJr02BRn0KfODw87Z68WKN3ij7eirkDSOYIbMgrTG4HAkEA2h/yLg6FJRE+ulxiZKqk19ANLYgNkjn0s8InwQK5UbN5/SjAzTtd/YYRTI5ikNkSoII3cGWNCKvqxekkJi6kTwJABBXuLgX1M+3FV8Zm/GYxOaMUWj0kVWUks2swOTjWtuXkTl2peok2MHlV99qgd4LBy7j3UzSbMiwCeuEVznfPmwJAWy6iNvNh3eP6DoKxX6hawxeA4NlZsWGwh+5SxrE2T7tfB5aiWKhSXn1N9u3fqEvreFdDtM+WwfxKohpdRsM5ag==";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.sellerID = seller;
    order.outTradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.subject = @"购买商品"; //商品标题
    order.body = product.body; //商品描述
    order.totalFee = [NSString stringWithFormat:@"%.2f",[self.tempData3 floatValue]]; //商品价格
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showURL = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"alisdkdemo";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
    }

    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
